<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>Ajax + Servlet 示例</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 24px; }
        input, textarea { display:block; margin:8px 0; width:300px; }
        #status { margin-top:8px; color: #333; }
    </style>
</head>
<body>
<h2>留言（XMLHttpRequest 示例）</h2>
<form id="msgForm">
    <input id="name" name="name" placeholder="姓名" required />
    <textarea id="message" name="message" placeholder="留言" rows="4" required></textarea>
    <button type="submit">发送</button>
</form>
<div id="status"></div>
<ul id="list"></ul>

<script>
    const status = document.getElementById('status');
    const list = document.getElementById('list');

    document.getElementById('msgForm').addEventListener('submit', function(e){
        e.preventDefault(); // 防止表单提交导致页面刷新

        const payload = {
            name: document.getElementById('name').value.trim(),
            message: document.getElementById('message').value.trim()
        };

        const xhr = new XMLHttpRequest();
        // 使用相对路径，假设 HTML 与 Servlet 在同一应用 (context)
        xhr.open('POST', 'api/message', true);
        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

        status.textContent = '发送中...';

        xhr.onreadystatechange = function() {
            if (xhr.readyState !== XMLHttpRequest.DONE) return;
            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    const res = JSON.parse(xhr.responseText);
                    if (res.ok) {
                        status.textContent = '发送成功';
                        addToList(res.message);
                    } else {
                        status.textContent = '服务器返回错误：' + (res.error || 'unknown');
                    }
                } catch (err) {
                    status.textContent = '解析返回值出错';
                }
            } else {
                status.textContent = 'HTTP 错误：' + xhr.status;
            }
        };

        xhr.onerror = function() { status.textContent = '网络错误'; };
        xhr.send(JSON.stringify(payload));
    });

    function addToList(msg) {
        const li = document.createElement('li');
        li.textContent = `${msg.name}：${msg.message}（${new Date(msg.timestamp).toLocaleString()}）`;
        list.appendChild(li);
    }

    // 页面加载时拉取已有留言（GET）
    fetch('api/message')
        .then(r => r.json())
        .then(res => { if (res.ok && res.messages) res.messages.forEach(addToList); })
        .catch(()=>{/* 忽略 */});
</script>
</body>
</html>
